package com.st.bottomnavigation.ui.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.st.bottomnavigation.R;
import com.st.bottomnavigation.global.sharedpreferences.STSharedPreferences;
import com.st.bottomnavigation.service.MyService;
import com.st.bottomnavigation.utils.Data;
import com.st.bottomnavigation.utils.DialogUtils;
import com.st.bottomnavigation.utils.RegexUtils;
import com.st.bottomnavigation.utils.RetrofitUtil;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//登录界面
public class LoginActivity extends AppCompatActivity {

    private EditText input_account;
    private EditText input_password;
    private EditText input_phone;
    private EditText input_code;
    private Button btn_send_code;
    private Button btn_login_account;
    //
    private MyService myService;//网络请求接口
    JSONObject param = new JSONObject();
    //
    final int DRAWABLE_RIGHT = 2;//密码可见图片位置：左：0,上：1,右：2,下：3
    boolean isPasswordVisible = false; // 记录密码是否可见
    private boolean isCountingDown = false; // 是否正在倒计时
    private CountDownTimer countDownTimer; // 倒计时器
    private LinearLayout ll_login_account;
    private LinearLayout ll_login_phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //初始化
        initView();
    }

    private void initView() {
        //状态栏设置
        getWindow().setStatusBarColor(getColor(R.color.transparent));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//字体黑色
        getSupportActionBar().hide();//隐藏标题栏
        //网络接口
        myService = RetrofitUtil.build(MyService.class);
        //
        input_account = findViewById(R.id.input_account);//账号
        input_password = findViewById(R.id.input_password);//密码
        input_phone = findViewById(R.id.input_phone);//手机号
        input_code = findViewById(R.id.input_code);//验证码
        //
        btn_login_account = findViewById(R.id.btn_login_account);//账号登陆按钮
        btn_send_code = findViewById(R.id.btn_send_code);//发送验证码按钮
        btn_login_account.setEnabled(false);//初始化不能点击
        //
        ll_login_account = findViewById(R.id.ll_login_account);//账号登陆-LinearLayout
        ll_login_phone = findViewById(R.id.ll_login_phone);//手机号登陆-LinearLayout
        //
        listener();
        initInput();
        checkInput();//验证登陆按钮是否可用

    }

    private void initInput() {
        String username = STSharedPreferences.getInstance(this).getUserName();
        String password = STSharedPreferences.getInstance(this).getPassword();
        if (Data.isNotNull(username)){
            input_account.setText(username);
        }
        if (Data.isNotNull(password)){
            input_password.setText(password);
        }
    }

    private void listener() {

        // 监听密码显示/隐藏切换按钮的点击事件
        input_password.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (event.getRawX() >= (input_password.getRight() - input_password.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width()/2)) {
                        // 点击了右侧图标
                        isPasswordVisible = !isPasswordVisible; // 切换密码可见状态

                        if (isPasswordVisible) {
                            // 显示明文
                            input_password.setInputType(InputType.TYPE_CLASS_TEXT);
                            input_password.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shape_icon_password, 0, R.drawable.shape_icon_password_show, 0);
                        } else {
                            // 显示密文
                            input_password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                            input_password.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shape_icon_password, 0, R.drawable.shape_icon_password_unshow, 0);
                        }
                        // 将光标移动到末尾
                        input_password.setSelection(input_password.getText().length());
                        return true;
                    }
                }
                return false;
            }
        });

        // 添加文本变化监听器
        input_account.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要处理
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 不需要处理
            }

            @Override
            public void afterTextChanged(Editable s) {
                checkInput();// 当账号和密码都有输入时启用登录按钮
            }
        });

        // 添加文本变化监听器
        input_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要处理
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 不需要处理
            }

            @Override
            public void afterTextChanged(Editable s) {
                checkInput();// 当账号和密码都有输入时启用登录按钮
            }
        });
    }

    @Override
    public void onBackPressed() {
        getSupportFragmentManager().popBackStack();
        super.onBackPressed();

    }

    /**
     * 当账号和密码都有输入时启用登录按钮
     */
    private void checkInput() {
        // 当账号和密码都有输入时启用登录按钮
        if (!TextUtils.isEmpty(input_account.getText().toString()) &&
                !TextUtils.isEmpty(input_password.getText().toString())) {
            btn_login_account.setEnabled(true);
            btn_login_account.setBackground(getResources().getDrawable(R.drawable.background_gradient_blue_btn1));
        } else {
            btn_login_account.setEnabled(false);
            btn_login_account.setBackground(getResources().getDrawable(R.drawable.background_gradient_blue_btn2));
        }
    }

    /**
     * 密码登录
     * @param view
     */
    public void accountLogin(View view) {
        String username = input_account.getText().toString();
        String password = input_password.getText().toString();
        if (Data.isNull(username) || Data.isNull(password)) {
            DialogUtils.show(this, "账号或密码不能为空");
        }
        param.put("username", username);
        param.put("password", password);
        myService.loginPassword(username,password).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    JSONObject data = RetrofitUtil.getDataFromResponse(response);
                    if (data != null && data.getInteger("code") == 200){
                        JSONObject result = data.getJSONObject("data");
                        JSONObject user = result.getJSONObject("user");
                        STSharedPreferences.getInstance(LoginActivity.this).saveUserName(param.getString("username"));
                        STSharedPreferences.getInstance(LoginActivity.this).savePassword(param.getString("password"));
                        STSharedPreferences.getInstance(LoginActivity.this).saveUser(user.toJSONString());
                        onBackPressed();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        });
    }

    /**
     * 跳转短信登录
     * @param view
     */
    public void toPhoneLogin(View view) {
        ll_login_phone.setVisibility(View.VISIBLE);
        ll_login_account.setVisibility(View.GONE);
    }

    /**
     * 跳转密码登录
     * @param view
     */
    public void toPasswordLogin(View view) {
        ll_login_phone.setVisibility(View.GONE);
        ll_login_account.setVisibility(View.VISIBLE);
    }

    /**
     * 发送短信
     * @param view
     */
    public void sendCode(View view) {
        String phone = input_phone.getText().toString();
        if (Data.isNull(phone)) {
            Toast.makeText(LoginActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (RegexUtils.isPhoneInvalid(phone)){
            Toast.makeText(LoginActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        hideKeyboard();// 隐藏软键盘
        if (!isCountingDown) {
            // 发送验证码
            myService.sendCode(phone).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        JSONObject data = RetrofitUtil.getDataFromResponse(response);
                        if (data != null && data.getInteger("code") == 200){
                            JSONObject result = data.getJSONObject("data");
                            String code = result.getString("phoneCode");
                            DialogUtils.show(LoginActivity.this, "验证码已发送，请注意查收:"+code);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable throwable) {

                }
            });
            startCountDownTimer();// 开始倒计时
        }
    }

    /**
     * 倒计时60s
     */
    private void startCountDownTimer() {
        isCountingDown = true;
        countDownTimer = new CountDownTimer(60000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                // 更新按钮文本为倒计时时间
                btn_send_code.setText(String.format("%d秒", millisUntilFinished / 1000));
                btn_send_code.setEnabled(false); // 禁用按钮
            }

            @Override
            public void onFinish() {
                // 倒计时结束，恢复按钮状态
                btn_send_code.setText("发送验证码");
                btn_send_code.setEnabled(true);
                isCountingDown = false;
            }
        }.start();
    }

    /**
     * 短信登录
     * @param view
     */
    public void phoneLogin(View view) {
        String phone = input_phone.getText().toString();
        String code = input_code.getText().toString();
        if (Data.isNull(phone) || Data.isNull(code)) {
            DialogUtils.show(this, "手机号或验证码不能为空");
        }
        myService.loginPhone(phone,code).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    JSONObject data = RetrofitUtil.getDataFromResponse(response);
                    if (data != null && data.getInteger("code") == 200){
                        JSONObject result = data.getJSONObject("data");
                        JSONObject user = result.getJSONObject("user");
                        STSharedPreferences.getInstance(LoginActivity.this).saveUser(user.toJSONString());
                        onBackPressed();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {

            }
        });
    }

    /**
     * 关闭软键盘
     */
    private void hideKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

}